#include <sdk.h>
#ifndef CB_PRECOMP
    #include <cbeditor.h>
    #include <configmanager.h>
    #include <editormanager.h>
    #include <logmanager.h>
    #include <projectmanager.h>
    #include <cbproject.h>
#endif
#include <wx/choicdlg.h>
#include <wx/textdlg.h>
#include <wx/dir.h>
#include <wx/file.h>
#include <wx/frame.h>
#include <wx/menu.h>
#include "AICoder.h"

namespace { PluginRegistrant<AICoder> reg(_T("AICoder")); }

BEGIN_EVENT_TABLE(AICoder, cbPlugin)
    EVT_MENU(wxID_ANY, AICoder::OnAIGenerateCode)
END_EVENT_TABLE()

AICoder::AICoder() 
    : m_aiMenu(nullptr)
    , m_collaborationMenu(nullptr)
    , m_collaborationRunning(false)
    , m_isInCollaborationSession(false)
{
}

AICoder::~AICoder()
{
    StopCollaboration();
}

void AICoder::OnAttach()
{
    Manager::Get()->GetLogManager()->Log(_("AICoder 插件已加载"));

    // 创建AI菜单
    m_aiMenu = new wxMenu;
    m_aiMenu->Append(wxID_ANY, _("生成代码"), _("AI生成代码"));
    m_aiMenu->Append(wxID_ANY, _("重构当前文件"), _("AI重构代码"));
    m_aiMenu->Append(wxID_ANY, _("分析项目"), _("AI分析项目结构"));
    m_aiMenu->AppendSeparator();
    m_aiMenu->Append(wxID_ANY, _("自我重构UEStudio"), _("AI重构UEStudio自身"));

    // 创建协作菜单
    m_collaborationMenu = new wxMenu;
    m_collaborationMenu->Append(wxID_ANY, _("加入协作会话"), _("加入AI模型协作开发"));
    m_collaborationMenu->Append(wxID_ANY, _("创建模型组件"), _("创建新的AI模型组件"));
    m_collaborationMenu->Append(wxID_ANY, _("发布组件"), _("发布组件到全局库"));
    m_collaborationMenu->Append(wxID_ANY, _("组件浏览器"), _("浏览可用组件"));

    // 初始化协作框架
    InitializeCollaborationFramework();
}

void AICoder::OnRelease(bool appShutDown)
{
    StopCollaboration();
}

void AICoder::BuildMenu(wxMenuBar* menuBar)
{
    // 在"View"菜单后添加AI菜单
    int pos = menuBar->FindMenu(_("View"));
    if (pos != wxNOT_FOUND)
    {
        menuBar->Insert(pos + 1, m_aiMenu, _("&AI编程"));
        menuBar->Insert(pos + 2, m_collaborationMenu, _("&AI协作"));
    }
}

void AICoder::BuildModuleMenu(const ModuleType type, wxMenu* menu, const FileTreeData* data)
{
    if (type == mtEditorManager)
    {
        menu->AppendSeparator();
        menu->Append(wxID_ANY, _("AI生成代码"), _("使用AI生成代码"));
        menu->Append(wxID_ANY, _("AI重构代码"), _("使用AI重构当前文件"));
        menu->AppendSeparator();
        menu->Append(wxID_ANY, _("加入AI协作"), _("加入AI模型协作开发"));
    }
}

// ========== 简化的功能实现 ==========

void AICoder::GenerateCode()
{
    cbEditor* editor = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
    if (!editor)
    {
        wxMessageBox(_("请先打开一个编辑器"), _("AICoder"));
        return;
    }

    wxString requirement = wxGetTextFromUser(
        _("请输入代码需求描述:"),
        _("AI代码生成")
    );

    if (requirement.IsEmpty())
        return;

    wxString generatedCode = CallDeepSeekAPI(requirement);
    
    // 简化实现：显示生成的代码
    wxMessageBox(wxString::Format(_("生成的代码:\n%s"), generatedCode), _("AICoder"));
}

void AICoder::RefactorCurrentFile()
{
    cbEditor* editor = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
    if (!editor)
    {
        wxMessageBox(_("请先打开一个编辑器"), _("AICoder"));
        return;
    }

    wxString instructions = wxGetTextFromUser(
        _("请输入重构指令:"),
        _("AI代码重构")
    );

    if (instructions.IsEmpty())
        return;

    wxString refactoredCode = CallDeepSeekAPI(instructions);
    wxMessageBox(wxString::Format(_("重构后的代码:\n%s"), refactoredCode), _("AICoder"));
}

wxString AICoder::CallDeepSeekAPI(const wxString& prompt)
{
    // 简化版API调用
    return wxString::Format(
        "// AI生成的代码\n// 需求: %s\n\n"
        "void ai_generated_function() {\n"
        "    // 这里是由AI生成的代码\n"
        "    // 需要配置DeepSeek API密钥以获得真实生成\n"
        "}\n",
        prompt
    );
}

wxString AICoder::GetCurrentFileContent()
{
    // 简化实现
    return wxString("// 当前文件内容");
}

// ========== 协作功能实现 ==========

void AICoder::InitializeCollaborationFramework()
{
    // 初始化实时编辑器
    m_realTimeEditor = std::make_unique<CRealTimeEditor>();
    SetupCollaborationCallbacks();
    Manager::Get()->GetLogManager()->Log(_("AICoder 协作框架已初始化"));
}

void AICoder::SetupCollaborationCallbacks()
{
    m_realTimeEditor->SetChangeCallback([this](const CollaborationMessage& msg) {
        wxString status = wxString::Format("协作更新来自 %s: %s", msg.GetSender(), msg.GetContent());
        UpdateCollaborationUI(status);
        Manager::Get()->GetLogManager()->Log(status);
    });
}

void AICoder::JoinCollaborationSession()
{
    wxString sessionId = wxGetTextFromUser(_("请输入协作会话ID:"), _("加入AI协作会话"));
    if (!sessionId.IsEmpty()) {
        m_isInCollaborationSession = true;
        wxMessageBox(wxString::Format(_("已加入协作会话: %s"), sessionId), _("AI协作"));
    }
}

void AICoder::CreateModelComponent()
{
    wxString componentName = wxGetTextFromUser(_("请输入组件名称:"), _("创建模型组件"));
    if (!componentName.IsEmpty()) {
        wxMessageBox(wxString::Format(_("组件 '%s' 创建成功！"), componentName), _("AI协作"));
    }
}

void AICoder::PublishComponent()
{
    wxMessageBox(_("组件发布功能开发中..."), _("AI协作"));
}

void AICoder::ShowComponentBrowser()
{
    auto& registry = CGlobalComponentRegistry::GetInstance();
    size_t count = registry.GetTotalComponentCount();
    wxMessageBox(wxString::Format(_("全局组件库中有 %zu 个组件"), count), _("组件浏览器"));
}

// ========== 事件处理 ==========

void AICoder::OnAIGenerateCode(wxCommandEvent& event) { GenerateCode(); }
void AICoder::OnAIRefactor(wxCommandEvent& event) { RefactorCurrentFile(); }
void AICoder::OnAIAnalyze(wxCommandEvent& event) { AnalyzeProject(); }
void AICoder::OnSelfRefactor(wxCommandEvent& event) { SelfRefactorUEStudio(); }
void AICoder::OnJoinCollaboration(wxCommandEvent& event) { JoinCollaborationSession(); }
void AICoder::OnCreateComponent(wxCommandEvent& event) { CreateModelComponent(); }
void AICoder::OnPublishComponent(wxCommandEvent& event) { PublishComponent(); }
void AICoder::OnShowComponentBrowser(wxCommandEvent& event) { ShowComponentBrowser(); }

// ========== 其他方法实现 ==========

void AICoder::AnalyzeProject() { 
    wxMessageBox(_("项目分析功能开发中..."), _("AICoder")); 
}

void AICoder::SelfRefactorUEStudio() { 
    wxMessageBox(_("自我重构功能开发中..."), _("AICoder")); 
}

void AICoder::StartCollaborationServer() {
    m_collaborationRunning = true;
    m_collaborationThread = std::thread(&AICoder::CollaborationThread, this);
}

void AICoder::CollaborationThread() {
    while (m_collaborationRunning) {
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }
}

void AICoder::StopCollaboration() { 
    m_collaborationRunning = false;
    if (m_collaborationThread.joinable()) {
        m_collaborationThread.join();
    }
}

void AICoder::HandleIncomingCollaboration(const CollaborationMessage& message) {
    Manager::Get()->GetLogManager()->Log(wxString::Format("收到协作消息: %s", message.GetContent()));
}

void AICoder::UpdateCollaborationUI(const wxString& status) {
    // 更新UI状态
}

wxString AICoder::GetCurrentDeveloperId() { 
    return wxString::Format("%s@%s", wxGetUserId(), wxGetHostName()); 
}

wxString AICoder::GetProjectStructure() {
    return wxString("// 项目结构信息");
}
